﻿
using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Data.Extensions;
using ModuleMegMES.Models;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ModuleMegMES.ViewModels
{
    public class ViewAViewModel : NavigationViewModel
    {
        #region 变量
        string partNum;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private RestClient client;
        #endregion
        #region 属性
        private bool isUseMES;
        public bool IsUseMES
        {
            get { return isUseMES; }
            set { SetProperty(ref isUseMES, value); }
        }
        private string equipmentNumber;
        public string EquipmentNumber
        {
            get { return equipmentNumber; }
            set { SetProperty(ref equipmentNumber, value); }
        }
        private string equipmentName;
        public string EquipmentName
        {
            get { return equipmentName; }
            set { SetProperty(ref equipmentName, value); }
        }
        private string equipmentSpec;
        public string EquipmentSpec
        {
            get { return equipmentSpec; }
            set { SetProperty(ref equipmentSpec, value); }
        }
        private string messageStr = string.Empty;
        public string MessageStr
        {
            get { return messageStr; }
            set { SetProperty(ref messageStr, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> mESSwitchCommand;
        public DelegateCommand<object> MESSwitchCommand =>
            mESSwitchCommand ?? (mESSwitchCommand = new DelegateCommand<object>(ExecuteMESSwitchCommand));
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));
        private DelegateCommand appLoadedEventCommand;
        public DelegateCommand AppLoadedEventCommand =>
            appLoadedEventCommand ?? (appLoadedEventCommand = new DelegateCommand(ExecuteAppLoadedEventCommand));

        void ExecuteAppLoadedEventCommand()
        {
            addMessage("加载完成");
        }
        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            if (obj is string str)
            {
                switch (str)
                {
                    case "EquipmentNumber":
                        {
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentNumber");
                            if (param != null)
                            {
                                param.Value = EquipmentNumber;
                            }
                            else
                            {
                                mdb.MParams.Add(new MParam { Name = "EquipmentNumber", Value = EquipmentNumber, Type = typeof(string).Name, Hand = 0 });
                            }
                            mdb.SaveChanges();
                        }
                        break;
                    case "EquipmentName":
                        {
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentName");
                            if (param != null)
                            {
                                param.Value = EquipmentName;
                            }
                            else
                            {
                                mdb.MParams.Add(new MParam { Name = "EquipmentName", Value = EquipmentName, Type = typeof(string).Name, Hand = 0 });
                            }
                            mdb.SaveChanges();
                        }
                        break;
                    case "EquipmentSpec":
                        {
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentSpec");
                            if (param != null)
                            {
                                param.Value = EquipmentSpec;
                            }
                            else
                            {
                                mdb.MParams.Add(new MParam { Name = "EquipmentSpec", Value = EquipmentSpec, Type = typeof(string).Name, Hand = 0 });
                            }
                            mdb.SaveChanges();
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        void ExecuteMESSwitchCommand(object obj)
        {
            if (obj is bool r)
            {
                using var mdb = new MDbContext(partNum);
                var param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
                if (param != null)
                {
                    param.Value = IsUseMES.ToString();
                }
                else
                {
                    mdb.MParams.Add(new MParam { Name = "IsUseMES", Value = IsUseMES.ToString(), Type = typeof(bool).Name, Hand = 0 });
                }
                mdb.SaveChanges();
            }
        }
        #endregion
        #region 构造函数
        public ViewAViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            client = new RestClient("http://172.23.232.65:9046/LH_EquipmentMoldApi/PostEquipmentData");
            aggregator.ResgiterMessage(arg =>
            {
                var strs = arg.Message.Split(new char[] { ';' });

                switch (strs[0])
                {
                    case "PartNum":
                        {
                            partNum = strs[1];
                            addMessage($"料号:{partNum}");
                            using var mdb = new MDbContext(partNum);
                            var param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentNumber");
                            if (param != null)
                            {
                                EquipmentNumber = param.Value;
                            }
                            else
                            {
                                EquipmentNumber = "0001";
                                mdb.MParams.Add(new MParam { Name = "EquipmentNumber", Value = EquipmentNumber, Type = typeof(string).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentName");
                            if (param != null)
                            {
                                EquipmentName = param.Value;
                            }
                            else
                            {
                                EquipmentName = "机台1";
                                mdb.MParams.Add(new MParam { Name = "EquipmentName", Value = EquipmentName, Type = typeof(string).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "EquipmentSpec");
                            if (param != null)
                            {
                                EquipmentSpec = param.Value;
                            }
                            else
                            {
                                EquipmentSpec = "spec1";
                                mdb.MParams.Add(new MParam { Name = "EquipmentSpec", Value = EquipmentSpec, Type = typeof(string).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                            param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
                            if (param != null)
                            {
                                IsUseMES = bool.Parse(param.Value);
                            }
                            else
                            {
                                IsUseMES = true;
                                mdb.MParams.Add(new MParam { Name = "IsUseMES", Value = IsUseMES.ToString(), Type = typeof(bool).Name, Hand = 0 });
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "UpLoad":
                        {
                            if (IsUseMES)
                            {
                                try
                                {
                                    List<Comparison> records = JsonConvert.DeserializeObject<List<Comparison>>(arg.Message.Substring(arg.Message.IndexOf(";") + 1, arg.Message.Length - (arg.Message.IndexOf(";") + 1)));
                                    List<string> barcodes = new List<string>();
                                    foreach (var item in records)
                                    {
                                        if (!barcodes.Contains(item.条码) && item.条码 != string.Empty)
                                        {
                                            barcodes.Add(item.条码.Substring(0, item.条码.Length));
                                        }
                                    }
                                    if (barcodes.Count > 0)
                                    {
                                        foreach (var bar in barcodes)
                                        {
                                            var _records = records.Where(p => p.条码 == bar);
                                            if (_records.Any())
                                            {
                                                bool r = UpLoad(bar, _records.ToArray());
                                                addMessage($"条码:{bar},上传{(r ? "成功" : "失败")}");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        addMessage("无条码");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    addMessage(ex.Message);
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }, "MES");
        }
        #endregion
        #region 功能函数
        private void addMessage(string str)
        {
            logger.Debug("MES:" + str);
            string[] s = MessageStr.Split('\n');
            if (s.Length > 1000)
            {
                MessageStr = "";
            }
            if (MessageStr != "")
            {
                MessageStr += "\n";
            }
            MessageStr += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + str;
        }
        private bool UpLoad(string barcode, Comparison[] _records)
        {
            List<Equipment> list = new List<Equipment>();
            Equipment equipment = new Equipment();
            equipment.Creator = "admin";
            equipment.CreateDate = DateTime.Now;
            equipment.Modifier = "";
            equipment.ModifyDate = null;
            equipment.ForbiddenStatus = false;
            string mainId = Guid.NewGuid().ToString();
            equipment.ID = mainId;
            equipment.EquipmentNumber = EquipmentNumber;
            equipment.EquipmentName = EquipmentName;
            equipment.EquipmentSpec = EquipmentSpec;
            equipment.Sn = barcode;
            for (int j = 0; j < _records.Length; j++)
            {
                EquipmentParameter item = new EquipmentParameter();
                item.Creator = "Root";
                item.CreateDate = DateTime.Now;
                item.Modifier = "";
                item.ModifyDate = null;
                item.ForbiddenStatus = false;
                item.ID = Guid.NewGuid().ToString();
                item.EquipmentId = mainId;
                item.ParameterName = $"{_records[j].焊接点}-功率";
                item.ParameterValue = $"{_records[j].功率}";
                item.UnitName = "W";
                equipment.ListParameter.Add(item);
            }
        
            for (int j = 0; j < _records.Length; j++)
            {
                EquipmentParameter item = new EquipmentParameter();
                item.Creator = "Root";
                item.CreateDate = DateTime.Now;
                item.Modifier = "";
                item.ModifyDate = null;
                item.ForbiddenStatus = false;
                item.ID = Guid.NewGuid().ToString();
                item.EquipmentId = mainId;
                item.ParameterName = $"{_records[j].焊接点}-速度";
                item.ParameterValue = $"{_records[j].速度}";
                item.UnitName = "mm/s";
                equipment.ListParameter.Add(item);
            }
            for (int j = 0; j < _records.Length; j++)
            {
                EquipmentParameter item = new EquipmentParameter();
                item.Creator = "Root";
                item.CreateDate = DateTime.Now;
                item.Modifier = "";
                item.ModifyDate = null;
                item.ForbiddenStatus = false;
                item.ID = Guid.NewGuid().ToString();
                item.EquipmentId = mainId;
                item.ParameterName = $"{_records[j].焊接点}-焦距";
                item.ParameterValue = $"{_records[j].焦距}";
                item.UnitName = "mm";
                equipment.ListParameter.Add(item);
            }
            list.Add(equipment);

            var request = new RestRequest(string.Empty,Method.Post);
            request.AddHeader("Content-Type", "application/json");
            request.AddParameter("application/json", JsonConvert.SerializeObject(list), ParameterType.RequestBody);
            var response = client.Execute(request);
            addMessage(response.Content);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return response.Content.ToUpper().Contains("OK");
            else
                return false;
        }

        #endregion
    }
}
